package com.lyw.GeoLocationClient;

import android.app.Activity;
import android.app.Application;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import cn.bmob.v3.Bmob;
import com.baidu.mapapi.SDKInitializer;
import com.easemob.EMCallBack;
import com.easemob.chatui.domain.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lyw.GeoLocationClient.utils.SharePreferenceUtil;
import com.lyw.GeoLocationClient.bmob.restapi.BmobApi;
import com.lyw.GeoLocationClient.db.GeotableDB;
import com.lyw.GeoLocationClient.db.MessageDB;
import com.lyw.GeoLocationClient.db.RecentDB;
import com.lyw.GeoLocationClient.service.EMUserManager;
import com.lyw.GeoLocationClient.service.LBSClient;
import com.lyw.GeoLocationClient.ui.NotificationHelper;
import com.easemob.chatui.DemoHXSDKHelper;
import timber.log.Timber;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class App extends Application {

    private static App mInstance = null;
    public static final String SRV_AK = "KMvNgpsyYG4Ebhkz4tmSBjsp";
    public static final String ADMIN_IMEI = "359250051541041";
//    public static final String ADMIN_IMEI = "868191022230682";
    public static final String SP_FILE_NAME = "config";

    public static final String API_KEY = "SEfNgHkdMItZet9mXb7LS2kt";
    public static final String SECRIT_KEY = "vb62M3OcMbYdBlRqPfo9d8k6U7lGOpnp";

    public static final String HX_CLIENT_ID = "YXA6iHyW4MjAEeSU1yP1VK7DWg";
    public static final String HX_CLIENT_SECRET = "YXA6PYi9pezDqoA0kF9OoWJy98xY1ek";

    public static final long TRACK_SERVICE_ID = 110322;

    private GeotableDB mGeotableDB;
    private MessageDB mMsgDB;
    private RecentDB mRecentDB;

    private Gson mGson;

    private static boolean isAdmin = false;
    public static final boolean DEBUG = true;
    private static String imei;

    private LBSClient mClient;
    private static NotificationHelper notify;
    private static SharePreferenceUtil mSpUtil;

    private List<Activity> mList = new LinkedList<Activity>();


    public static Context applicationContext;
    private static App instance;
    // login user name
    public final String PREF_USERNAME = "username";

    /**
     * 当前用户nickname,为了苹果推送不是userid而是昵称
     */
    public static String currentUserNick = "";
    public static DemoHXSDKHelper hxSDKHelper = new DemoHXSDKHelper();



    public static String getImei() {
        return imei;
    }

    public static boolean isAdmin() {
        return isAdmin;
//        return false;
    }

    public static SharePreferenceUtil getSpUtil() {
        return mSpUtil;
    }

    private static EMUserManager emUserManager;

    public static EMUserManager getEmUserManager() {
        return emUserManager;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        applicationContext = this;
        instance = this;

        if (DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }

        SDKInitializer.initialize(this);
        //start LBS client;
        Intent intent = new Intent(this, LBSClient.class);
        startService(intent);

        notify = NotificationHelper.getInstance(this);
        mSpUtil = new SharePreferenceUtil(this, SP_FILE_NAME);

        mGeotableDB = new GeotableDB(this);

        checkAdminImei();

        emUserManager = new EMUserManager(this);

        hxSDKHelper.onInit(applicationContext);

        BmobApi.initBmob("b4fad5591d4a7dfdf530f158f67bcf88",
                "1582274933603e191c6561b972d831be");
        Bmob.initialize(this, "b4fad5591d4a7dfdf530f158f67bcf88");
    }

    public static App getInstance() {
        return mInstance;
    }

    public static boolean checkAdminImei() {
        TelephonyManager tm = (TelephonyManager) mInstance.getSystemService(TELEPHONY_SERVICE);
//        imei = tm.getLine1Number();
        imei = tm.getDeviceId();
        Timber.d( "imei:" + imei);
        if (imei.equals(ADMIN_IMEI)) {
            isAdmin = true;
        }
        return false;
    }

    public static void setIsAdmin(boolean b) {
        isAdmin = b;
    }

    public synchronized Gson getGson() {
        if (mGson == null)
            // 不转换没有 @Expose 注解的字段
            mGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
                    .create();
        return mGson;
    }

    /**
     * 设置手机网络类型，wifi，cmwap，ctwap，用于联网参数选择
     * @return
     */
    static String setNetworkType() {
        String networkType = "wifi";
        ConnectivityManager manager = (ConnectivityManager) mInstance
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netWrokInfo = manager.getActiveNetworkInfo();
        if (netWrokInfo == null || !netWrokInfo.isAvailable()) {
            // 当前网络不可用
            return "";
        }

        String info = netWrokInfo.getExtraInfo();
        if ((info != null)
                && ((info.trim().toLowerCase().equals("cmwap"))
                || (info.trim().toLowerCase().equals("uniwap"))
                || (info.trim().toLowerCase().equals("3gwap")) || (info
                .trim().toLowerCase().equals("ctwap")))) {
            // 上网方式为wap
            if (info.trim().toLowerCase().equals("ctwap")) {
                // 电信
                networkType = "ctwap";
            } else {
                networkType = "cmwap";
            }

        }
        return networkType;
    }

    public void addActivity(Activity activity) {
        mList.add(activity);
    }

    public void exit() {
        try {
            for (Activity activity : mList) {
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

    public synchronized GeotableDB getGeotableDB() {
        if (mGeotableDB == null)
            mGeotableDB = new GeotableDB(this);
        return mGeotableDB;
    }

    public synchronized RecentDB getRecentDB() {
        if (mRecentDB == null)
            mRecentDB = new RecentDB(this);
        return mRecentDB;
    }

    public synchronized MessageDB getMessageDB() {
        if (mMsgDB == null)
            mMsgDB = new MessageDB(this);
        return mMsgDB;
    }


    public static NotificationHelper getNotify() {
        return notify;
    }

    /**
     * 获取内存中好友user list
     *
     * @return
     */
    public Map<String, User> getContactList() {
        return hxSDKHelper.getContactList();
    }

    /**
     * 设置好友user list到内存中
     *
     * @param contactList
     */
    public void setContactList(Map<String, User> contactList) {
        hxSDKHelper.setContactList(contactList);
    }

    /**
     * 获取当前登陆用户名
     *
     * @return
     */
    public String getUserName() {
        return hxSDKHelper.getHXId();
    }

    /**
     * 获取密码
     *
     * @return
     */
    public String getPassword() {
        return hxSDKHelper.getPassword();
    }

    /**
     * 设置用户名
     *
     * @param username
     */
    public void setUserName(String username) {
        hxSDKHelper.setHXId(username);
    }

    /**
     * 设置密码 下面的实例代码 只是demo，实际的应用中需要加password 加密后存入 preference 环信sdk
     * 内部的自动登录需要的密码，已经加密存储了
     *
     * @param pwd
     */
    public void setPassword(String pwd) {
        hxSDKHelper.setPassword(pwd);
    }

    /**
     * 退出登录,清空数据
     */
    public void logout(final EMCallBack emCallBack) {
        // 先调用sdk logout，在清理app中自己的数据
        hxSDKHelper.logout(emCallBack);
    }

    /***
     * Android L (lollipop, API 21) introduced a new problem when trying to invoke implicit intent,
     * "java.lang.IllegalArgumentException: Service Intent must be explicit"
     *
     * If you are using an implicit intent, and know only 1 target would answer this intent,
     * This method will help you turn the implicit intent into the explicit form.
     *
     * Inspired from SO answer: http://stackoverflow.com/a/26318757/1446466
     * @param context
     * @param implicitIntent - The original implicit intent
     * @return Explicit Intent created from the implicit original intent
     */
    public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);

        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            return null;
        }

        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        ComponentName component = new ComponentName(packageName, className);

        // Create a new intent. Use the old one for extras and such reuse
        Intent explicitIntent = new Intent(implicitIntent);

        // Set the component to be explicit
        explicitIntent.setComponent(component);

        return explicitIntent;
    }
}
